<?php
require 'Xiachufang/entity/Food.php';
class FoodController extends BaseController {
	/**
	 * 显示食物的页面
	 *
	 */
	function indexAction() {
		$foodId = (int)$this->_getParam('foodId');
		if ($foodId <= 0) notFound();
		
		require_once 'Xiachufang/util/TimeUtil.php';
		$food = new FoodEntity();
		if (!$food->get($foodId)) notFound();
		
		// 获取评论列表
		require 'Xiachufang/logic/Remark.php';
		$remarks = RemarkLogic::getFoodRemarks($foodId);
		$remarkList = array();
		foreach($remarks as $row) {
			$actorId = $row["actor_id"];
			$actor = new ActorEntity();
			$actorName = "未知";
			if ($actor->get($actorId)) {
				$actorName = $actor->nickname;
			}
			$remarkList[] = array(
				"remarkId"=>$row["remark_id"],
				"actorId"=>$actorId,
				"actorName" => $actorName,
				"content" => $row["content"],
				"createTime" => TimeUtil::format($row["create_time"]),
			);
		}
		
		// 获取创建该食物的用户
		$actor = new ActorEntity();
		if ($actor->get($food->actorId)) {
			$this->smarty->assign("actor", $actor->getDataArray(array("actorId", "nickname")));
		}
		// 获取该食物对应的菜谱
		require_once 'Xiachufang/entity/Recipe.php';
		$recipe = new RecipeEntity();
		if ($recipe->get($food->recipeId)) {
			$this->smarty->assign("recipe",$recipe->getDataArray(array("recipeId","name")));
		}
		// 获取创建该食物的用户的其他食物
		require 'Xiachufang/logic/Food.php';
		$foodIds = FoodLogic::getActorFoodIds($food->actorId);
		$foodIds = array_diff($foodIds, array($food->foodId));
		$foodList = array();
		foreach($foodIds as $id) {
			$foodEntity = new FoodEntity();
			if (!$foodEntity->get($id)) continue;
			$foodList[] = $foodEntity->getDataArray(array("foodId","name"));
		}
		
		$this->smarty->assign(array(
			"isMyself"=>$food->actorId == $this->_actorId,
			"food"=>$food->getDataArray(),
			"pageTitle"=>$food->name,
			"pageDescription"=>$food->description,
		));
		$this->smarty->assign_by_ref("remarkList", $remarkList);
		$this->smarty->assign_by_ref("foodList", $foodList);
		$this->display();
	}
	
	/**
	 * 编辑食物
	 *
	 */
	function editAction() {
		$this->checkLogin();
		$foodId = (int)$this->_getParam('foodId');
		if ($foodId <= 0) notFound();
		
		$food = new FoodEntity();
		if (!$food->get($foodId)) alert("不存在foodId=$foodId的做过的菜谱");
		// 检查用户是否能编辑此食物
		$actorId = $this->_actorId;
		if ($actorId != $food->actorId) alert("你没有做过该菜谱");
		
		require 'Xiachufang/logic/Tag.php';
		$allTags = TagLogic::getHotTags(20, $recipeId);
		$myTags = TagLogic::getActorHotTags(20, $actorId);
		$this->smarty->assign_by_ref("allTags", $allTags);
		$this->smarty->assign_by_ref("myTags", $myTags);
		
		
		$data = $food->getDataArray();
		$data["tags"] = str_replace(",", " ", $data["tags"]);
		$this->smarty->assign(array(
			"pageTitle"=>"编辑做过的“".$food->name."”",
			"food"=>$data,
			"typeId"=>1,
		));
		$this->display();
	}
}
?>